package org.example.top40;

public class main13 {
    //搜索旋转排序有序数组
    //输入：nums = [4,5,6,7,0,1,2], target = 0 输出：4
    //思路：while(l<=r) 只找有序部分；nums[l]<=nums[mid] 前半有序 在此段中r收缩 不在l收缩
    public static void main(String[] args) {
        int[] nums={4,5,6,7,0,1,2};
        int target=0;
        int res=search(nums,target);
        System.out.println(res);
    }

    private static int search(int[] nums, int target) {
        int l=0;
        int r=nums.length-1;
        while (l<=r){
            int mid=l+(r-l)/2;
            if(nums[mid]==target){
                return mid;
            }
            if(nums[l]<=nums[mid]){
                if(target>=nums[l]&&target<nums[mid]){
                    r=mid-1;
                }else {
                    l=mid+1;
                }
            }else {
                if(target<=nums[r]&&target>nums[mid]){
                    l=mid+1;
                }else {
                    r=mid-1;
                }
            }
        }
        return -1;
    }
}
